<script setup lang="ts">
import {chatExchangeApi} from "@/api/chat_exchange";
import {useMessage} from 'naive-ui'
import {useUserStore} from "@/store";

const msg = useMessage()
const userStore = useUserStore()

interface Props {
	immediateExchangeShow: boolean
}

interface Emit {
	(e: 'update:immediateExchangeShow', immediateExchangeShow: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emit>()
const immediateExchangeShow = computed({
	get: () => props.immediateExchangeShow,
	set: (immediateExchangeShow: boolean) => emit('update:immediateExchangeShow', immediateExchangeShow),
})

// 兑换码
const exchangeCode = ref<string>('')

// 去兑换
const toExchange = async () => {
	if (exchangeCode.value != '') {
		try {
			const exchangeTimes = await chatExchangeApi.immediateExchangeConversation(exchangeCode.value)
			msg.success(`恭喜您，兑换了${exchangeTimes}次聊天`, {duration: 3000})
			immediateExchangeShow.value = false
			await userStore.getUserData()
		} catch (e: any) {
			msg.error(e.message, {duration: 1500})
		} finally {
			exchangeCode.value = ''
		}
	}
}

</script>

<template>
	<NModal v-model:show="immediateExchangeShow" style="width: 90%; max-width: 480px;" preset="card"
					title="兑换码兑换"
	>
		<div class="space-y-4">
			<div style="margin-top:26px">
				<NInput v-model:value="exchangeCode" type="text" placeholder="请输入兑换码" :maxlength="20"/>
				<NButton block style="margin-top:26px" @click="toExchange">
					立即兑换
				</NButton>
			</div>
		</div>
	</NModal>
</template>
